package controllers

import (
	"encoding/json"
	"film/models"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type FilmController struct {
	beego.Controller
}

func (c *FilmController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	title := c.GetString("title")
	query := models.DB.Model(&models.Film{})
	if title != "" {
		query = query.Where("title like ?", "%"+title+"%")
	}
	key := "film-" + strconv.Itoa(page) + "-" + title
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})

	if err != nil {
		var count int64
		err = query.Count(&count).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "总数据查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}

		offset := (page - 1) * size
		var film []models.Film
		err = query.Offset(offset).Limit(size).Find(&film).Error
		pageData["count"] = count
		pageData["film"] = film
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "数据查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(&pageData)
			value := string(marshal)
			models.Rdb.Set(key, value, time.Second*10)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "mysql查询成功",
				Data: pageData,
			}
			c.ServeJSON()
			return
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "redis查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *FilmController) Add() {
	title := c.GetString("title")
	img := c.GetString("img")
	status := c.GetString("status")
	num, _ := c.GetInt("num")
	zt := c.GetString("zt")
	time := c.GetString("time")
	if title == "" || img == "" || status == "" || num == 0 || zt == "" || time == "" {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请把数据填完整",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	film := models.Film{
		Title:  title,
		Img:    img,
		Status: zt,
		Num:    num,
		Zt:     status,
		Time:   time,
	}
	err := models.DB.Create(&film).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "数据添加成功",
			Data: film,
		}
		c.ServeJSON()
	}
}

func (c *FilmController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	ext := strings.ToLower(filepath.Ext(header.Filename))
	allowExt := map[string]bool{
		".png": true,
		".jpg": true,
	}
	if !allowExt[ext] {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件格式不正确",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if header.Size > 5*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件过大",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	path := "static/img" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "文件上传成功",
			Data: img,
		}
		c.ServeJSON()
	}
}

func (c *FilmController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("ID = ?", id).Delete(&models.Film{}).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "数据删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := "film-" + strconv.Itoa(id)
		models.Rdb.Del(key)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: id,
		}
		c.ServeJSON()
	}

}

func (c *FilmController) Upt() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	img := c.GetString("img")
	status := c.GetString("status")
	num, _ := c.GetInt("num")
	zt := c.GetString("zt")
	time := c.GetString("time")
	film := models.Film{
		Title:  title,
		Img:    img,
		Status: status,
		Num:    num,
		Zt:     zt,
		Time:   time,
	}
	err := models.DB.Debug().Where("ID = ?", id).Updates(&film).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: film,
		}
		c.ServeJSON()
	}
}

func (c *FilmController) Info() {
	id, _ := c.GetInt("id")
	Rankkey := "Rank"
	models.Rdb.ZIncrBy(Rankkey, 1, strconv.Itoa(id))
	key := "film-" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	var fiml models.Film
	if err != nil {
		err = models.DB.Model(&models.Film{}).Where("ID = ?", id).First(&fiml).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "详情查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(fiml)
			value := string(marshal)
			models.Rdb.Set(key, value, time.Second*10)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "mysql详情查询成功",
				Data: fiml,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &fiml)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "redis详情查询成功",
			Data: fiml,
		}
		c.ServeJSON()
	}

}
